package com.yzkj.cpjxc.business.controller;

import com.yzkj.cpjxc.business.constants.SysDeptConstants;
import com.yzkj.cpjxc.business.domain.SysDept;
import com.yzkj.cpjxc.business.domain.SysDeptShowVo;
import com.yzkj.cpjxc.business.domain.ZTreeComm;
import com.yzkj.cpjxc.business.framework.common.BusinessMap;
import com.yzkj.cpjxc.business.framework.common.CSRFTokenManager;
import com.yzkj.cpjxc.business.framework.common.Constants;
import com.yzkj.cpjxc.business.framework.common.Pager;
import com.yzkj.cpjxc.business.framework.utils.CollectionHelp;
import com.yzkj.cpjxc.business.framework.utils.IDUtils;
import com.yzkj.cpjxc.business.framework.utils.StringHelp;
import com.yzkj.cpjxc.business.service.SysDeptService;
import com.yzkj.cpjxc.business.domain.SysUser;
import com.yzkj.cpjxc.business.service.SysUserService;
import com.yzkj.cpjxc.business.system.interceptor.DoLog;
import com.yzkj.cpjxc.business.system.interceptor.Permission;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * 部门管理控制器
 */
@Controller
@RequestMapping("/sysDept")
public class SysDeptController extends BaseController {

	@Autowired
	private SysDeptService sysDeptService;
	
	@Autowired
	private SysUserService sysUserService;

	/**
	 * 去到部门管理列表页面
	 */
	@RequestMapping("/list")
	@DoLog(cnContent = "查看部门管理列表信息")
	@Permission(name = "sysDept.view")
	public ModelAndView list(HttpServletRequest request, HttpServletResponse response, SysDept sysDept) throws Exception {
		HashMap<String, Object> modelMap = new LinkedHashMap<String, Object>();
		modelMap.put("sysDept", sysDept);
		modelMap.put("csrfToken", CSRFTokenManager.getTokenForSession(request.getSession()));
		return new ModelAndView("sysMgr/securityMgr/sysDept/list").addAllObjects(modelMap);
	}

	/**
	 * 部门管理列表ajax分页
	 */
	@RequestMapping("/ajaxPage")
	@DoLog(cnContent = "部门管理列表ajax分页")
	@Permission(name = "sysDept.view")
	public String ajaxPage(HttpServletRequest request, HttpServletResponse response, SysDept sysDept) throws Exception {
		try {
			Pager<SysDeptShowVo> p = new Pager<SysDeptShowVo>();
			boolean exportExcel = BooleanUtils.toBoolean(request.getParameter(EXPORT_EXCEL));
			if (exportExcel) {
				return null;
			} else {
				String currentPage = request.getParameter(Pager.MY_PAGINATION_CURRENT_PAGE);
				p.setCurrentPage(Integer.parseInt(currentPage == null ? "1" : currentPage));
				Pager<SysDeptShowVo> pager = sysDeptService.search(p, sysDept);
				this.genPageJson(response, pager);
				return null;
			}
		} catch (Exception e) {
			this.logException(e);
			return this.ajax(response, "系统出现异常: [" + e.getMessage() + "] 请与管理员联系！");
		}
	}

	/**
	 * 去到添加部门管理页面
	 */
	@RequestMapping("/toAdd")
	@DoLog(cnContent = "去到添加部门管理页面")
	@Permission(name = "sysDept.add")
	public ModelAndView toAdd(HttpServletRequest request, HttpServletResponse response, SysDept sysDept) throws Exception {
		HashMap<String, Object> modelMap = new LinkedHashMap<String, Object>();
		modelMap.put("fictionMap", SysDeptConstants.getFictionMap());
		modelMap.put("statisticsMap", SysDeptConstants.getStatisticsMap());
		modelMap.put("sysDept", sysDept);
		modelMap.put("csrfToken", CSRFTokenManager.getTokenForSession(request.getSession()));
		return new ModelAndView("sysMgr/securityMgr/sysDept/add").addAllObjects(modelMap);
	}

	/**
	 * 添加部门管理
	 */
	@RequestMapping("/add")
	@DoLog(cnContent = "添加部门管理", operationAction = "C")
	@Permission(name = "sysDept.add")
	public String add(HttpServletRequest request, HttpServletResponse response, SysDept sysDept) throws Exception {
		try {
			
			//过滤指定非法字符
			StringHelp.replaceFilteringChars(SysDept.class, sysDept);
			
			sysDept.setDeptId(IDUtils.genUUID());
			sysDept.setDeleteFlag(Constants.DELETE_FLAG_NO);
			//查询父级拼接当前新增部门层级ID代码
			SysDeptShowVo parentDept = sysDeptService.getById(sysDept.getParentDeptId());
			if (parentDept != null) {
				if (StringUtils.isNotBlank(parentDept.getDeptLevelCode())) {
					sysDept.setDeptLevelCode(parentDept.getDeptLevelCode() + "-" + sysDept.getDeptId());
				}
			} else {
				//查询是否已经存在顶级部门，如果已存在，则不允许继续添加顶级部门(只允许存在一个顶级部门，顶级部门的父级部门ID为空)
				SysDept topLevelDept = sysDeptService.getTopLevelDept();
				if (topLevelDept != null) {
					return this.ajax(response, "必须选择添加一个上级部门！");
				} else {
					//如果没有存在顶级部门，则可以添加顶级部门
					//设置顶级部门旳父类部门ID为空
					sysDept.setParentDeptId(null);
					//设置顶级部门层级ID代码为其部门ID
					sysDept.setDeptLevelCode(sysDept.getDeptId());
				}
			}
			
			BusinessMap bm = sysDeptService.create(sysDept);
			return this.ajax(response, bm.getIsSucc() ? Constants.SUCCESS : bm.getAlertMesg());
		} catch (Exception e) {
			this.logException(e);
			return this.ajax(response, "系统出现异常: [" + e.getMessage() + "] 请与管理员联系！");
		}
	}

	/**
	 * 去到编辑部门管理页面
	 */
	@RequestMapping("/toEdit")
	@DoLog(cnContent = "去到编辑部门管理页面")
	@Permission(name = "sysDept.edit")
	public ModelAndView toEdit(HttpServletRequest request, HttpServletResponse response, SysDept sysDept) throws Exception {
		SysDeptShowVo result = sysDeptService.getById(sysDept.getDeptId());
		HashMap<String, Object> modelMap = new LinkedHashMap<String, Object>();
		modelMap.put("csrfToken", CSRFTokenManager.getTokenForSession(request.getSession()));
		modelMap.put("fictionMap", SysDeptConstants.getFictionMap());
		modelMap.put("statisticsMap", SysDeptConstants.getStatisticsMap());
		modelMap.put("sysDeptShowVo", result);
		return new ModelAndView("sysMgr/securityMgr/sysDept/edit").addAllObjects(modelMap);
	}

	/**
	 * 编辑部门管理
	 */
	@RequestMapping("/edit")
	@DoLog(cnContent = "编辑部门管理", operationAction = "U")
	@Permission(name = "sysDept.edit")
	public String edit(HttpServletRequest request, HttpServletResponse response, SysDept sysDept) throws Exception {
		try {
			
			//过滤指定非法字符
			StringHelp.replaceFilteringChars(SysDept.class, sysDept);
			
			//判断如果修改的是顶级部门,则不允许顶级部门有上一级部门(也就是上级部门ID不许为空)
			SysDeptShowVo dept = sysDeptService.getById(sysDept.getDeptId());
			//如果上级部门ID为空,则认为修改的对象为顶级部门
			if(dept != null && StringUtils.isBlank(dept.getParentDeptId())){
				if(StringUtils.isNotBlank(sysDept.getParentDeptId())){
					return this.ajax(response, "不能非法修改加入顶级部门的上级部门ID");
				}
			}
			BusinessMap bm = sysDeptService.edit(sysDept);
			return this.ajax(response, bm.getIsSucc() ? Constants.SUCCESS : bm.getAlertMesg());
		} catch (Exception e) {
			this.logException(e);
			return this.ajax(response, "系统出现异常: [" + e.getMessage() + "] 请与管理员联系！");
		}
	}

	/**
	 * 查看部门管理信息
	 */
	@RequestMapping("/view")
	@DoLog(cnContent = "查看部门管理信息")
	@Permission(name = "sysDept.view")
	public ModelAndView view(HttpServletRequest request, HttpServletResponse response, SysDept sysDept) throws Exception {
		SysDeptShowVo result = sysDeptService.getById(sysDept.getDeptId());

		result.setIsFictionName(SysDeptConstants.getFictionMap().get(result.getIsFiction()));
		result.setIsStatisticsName(SysDeptConstants.getStatisticsMap().get(result.getIsStatistics()));

		return new ModelAndView("sysMgr/securityMgr/sysDept/view").addObject("sysDeptShowVo", result);
	}

	/**
	 * 删除部门管理信息
	 */
	@RequestMapping("/delete")
	@DoLog(cnContent = "删除部门管理信息", operationAction = "D")
	@Permission(name = "sysDept.delete")
	public String delete(HttpServletRequest request, HttpServletResponse response, SysDept sysDept) throws Exception {
		try {
			SysDeptShowVo dept = sysDeptService.getById(sysDept.getDeptId());
			//1.不能删除顶级部门信息(顶级部门的上级部门空值)
			if (dept != null && StringUtils.isBlank(dept.getParentDeptId())) {
				return this.ajax(response, "无权限删除顶级部门信息！");
			}
			//2.如果当前部门有下属部门信息,则不能删除
			List<SysDeptShowVo> list = sysDeptService.getChlidDeptList(sysDept.getDeptId());
			if(CollectionHelp.isNotBank(list)){
				return this.ajax(response, "当前部门存在有关联的下级部门,不能删除！");
			}
			//3.部门下有关联用户信息(有效的用户),则不能删除
			boolean hasUserByDept = sysUserService.isHasUserByDept(sysDept.getDeptId());
			if(hasUserByDept){
				return this.ajax(response, "当前部门下有关联用户信息,不能删除！");
			}
			boolean flag = sysDeptService.delete(sysDept.getDeptId());
			return this.ajax(response, flag ? Constants.SUCCESS : Constants.ERROR);
		} catch (Exception e) {
			this.logException(e);
			return this.ajax(response, "系统出现异常: [" + e.getMessage() + "] 请与管理员联系！");
		}
	}

	/**
	 * @description: 部门树>>注：这是公用的别的页面可能调用的方法，所以这里不做权限控制
	 */
	@RequestMapping("/deptTree")
	@DoLog(cnContent = "部门树", value = false)
	public String deptTree(HttpServletRequest request, HttpServletResponse response, ZTreeComm tree) throws Exception {
		try {
			// 1.获取权限列表
			List<ZTreeComm> voList = sysDeptService.queryRootDeptTreeList(tree.getId());
			// 2.设置父节点
			for (int i = 0; i < voList.size(); i++) {
				if (sysDeptService.isParent(voList.get(i).getId())) {
					voList.get(i).setIsParent(Constants.IS_TRUE);
				} else {
					voList.get(i).setIsParent(Constants.IS_FALSE);
				}
			}
			return this.ajax(response, voList);
		} catch (Exception e) {
			this.logException(e);
			return this.ajax(response, "系统出现异常: [" + e.getMessage() + "] 请与管理员联系！");
		}
	}
	
	@RequestMapping("/toGetUserByDeptId")
	@DoLog(cnContent = "查看部门下的用户列表")
	public ModelAndView toGetUserByDeptId(HttpServletRequest request, HttpServletResponse response, SysDept sysDept) throws Exception {
		SysDeptShowVo result = sysDeptService.getById(sysDept.getDeptId());

		result.setIsFictionName(SysDeptConstants.getFictionMap().get(result.getIsFiction()));
		result.setIsStatisticsName(SysDeptConstants.getStatisticsMap().get(result.getIsStatistics()));

		return new ModelAndView("sysMgr/securityMgr/sysDept/relevanceUser").addObject("sysDept", result);
	}
	
	/**
	 * 初始化前面有checkbox的下拉部门树
	 * <pre><font color="red"><b>注：这是公用的别的页面可能调用的方法，所以这里不做权限控制</b></font></pre>
	 */
	@RequestMapping("/initCanCheckDeptTree")
	@DoLog(cnContent = "初始化前面有checkbox的下拉部门树树", value = false)
	public String initCanCheckDeptTree(HttpServletRequest request, HttpServletResponse response, ZTreeComm tree,String userId) throws Exception {
		try {
			
			SysUser user = sysUserService.getById(userId);
			List<SysDept> sysDepts = null;
			if(user!=null){
				sysDepts = user.getSysDepts();
			}
			
			List<ZTreeComm> voList = sysDeptService.queryRootDeptTreeList(tree.getId());
			// 2.设置父节点
			for (int i = 0; i < voList.size(); i++) {
				if (sysDeptService.isParent(voList.get(i).getId())) {
					voList.get(i).setIsParent(Constants.IS_TRUE);
				} else {
					voList.get(i).setIsParent(Constants.IS_FALSE);
				}
				if(CollectionHelp.isNotBank(sysDepts)){
					for(SysDept sd : sysDepts){
						if(sd.getDeptId().equals(voList.get(i).getId())){
							voList.get(i).setChecked(Constants.IS_TRUE);
						}
					}
				}
			}
			return this.ajax(response, voList);
		} catch (Exception e) {
			this.logException(e);
			return this.ajax(response, "系统出现异常: [" + e.getMessage() + "] 请与管理员联系！");
		}
	}
	
}
